package com.aube.interact.fighter.card;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aube.interact.fighter.R;
import com.aube.interact.fighter.control.DataManager;
import com.aube.interact.fighter.model.GameConfig;
import com.aube.interact.fighter.model.OptionResultModel;
import com.aube.interact.fighter.model.ReportResultModel;
import com.aube.interact.fighter.model.TimeLinePiece;
import com.aube.interact.fighter.model.VoteInfo;
import com.aube.interact.fighter.model.VoteItemInfo;
import com.aube.interact.fighter.roundedimageview.RoundedImageView;
import com.aube.interact.fighter.util.AnimatorHelper;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.Utils;

/**
 * Created by huyaonan on 16/11/15.
 */
public class CardGuess extends BaseCardNew implements View.OnClickListener {

    private LinearLayout mGuessLayout;

    private ImageView mRedState, mBlueState, mRedWin, mBlueWin;
    private TextView mRedTitle, mBlueTitle, mRedRate, mBlueRate;
    private VSProgressView mProgress;
    private RoundedImageView mRedLogo, mBlueLogo;

    private VoteInfo mVoteInfo;

    private int selectedIndex = -1;

    public CardGuess(Context context) {
        this(context, null);
    }

    public CardGuess(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CardGuess(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        LayoutInflater.from(context).inflate(R.layout.aube_intera_card_guess, this, true);

        mTitle = (TextView) findViewById(R.id.card_title);
        mDesp = (TextView) findViewById(R.id.card_desp);
        mFoldStateTxt = (TextView) findViewById(R.id.card_foldorexpand_text);

        mCollapse = (ImageView) findViewById(R.id.card_foldorexpand_img);
        mDespLayout = findViewById(R.id.card_desp_layout);

        mGuessLayout = (LinearLayout) findViewById(R.id.card_detail_layout);

        mClose = (ImageView) findViewById(R.id.card_close);
        mClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });

        mDespLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                swithWindow(mGuessLayout.getVisibility() == View.VISIBLE, mGuessLayout);
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mContentHeight <= 0) {
            mGuessLayout.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            mContentHeight = mGuessLayout.getMeasuredHeight();
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public void init(TimeLinePiece data, ChannelDetail channelDetail) {
        super.init(data, channelDetail);

        mTitle.setText(data.title);

        mRedLogo = (RoundedImageView) findViewById(R.id.vs_red_logo);
        mRedState = (ImageView) findViewById(R.id.vs_red_state);
        mBlueLogo = (RoundedImageView) findViewById(R.id.vs_blue_logo);
        mBlueState = (ImageView) findViewById(R.id.vs_blue_state);
        mRedTitle = (TextView) findViewById(R.id.vs_red_txt);
        mBlueTitle = (TextView) findViewById(R.id.vs_blue_txt);
        mProgress = (VSProgressView) findViewById(R.id.vs_progress);
        mRedRate = (TextView) findViewById(R.id.vs_red_rate_txt);
        mBlueRate = (TextView) findViewById(R.id.vs_blue_rate_txt);
        mRedWin = (ImageView) findViewById(R.id.vs_red_win);
        mBlueWin = (ImageView) findViewById(R.id.vs_blue_win);

        if(data.hasImgInOption()) {
            mRedLogo.setVisibility(View.VISIBLE);
            mBlueLogo.setVisibility(View.VISIBLE);

            ImageLoader.getInstance(getContext()).fillImage(mRedLogo, mData.getOptionImgUrl(0));
            ImageLoader.getInstance(getContext()).fillImage(mBlueLogo, mData.getOptionImgUrl(1));
        } else {
            mRedLogo.setVisibility(View.GONE);
            mBlueLogo.setVisibility(View.GONE);
        }

        selectedIndex = DataManager.getInstance(getContext()).getIndex(data.getRid());
        mVoteInfo = parse(data);

        mRedTitle.setText(mVoteInfo.getContents().get(0).getSubject());
        mBlueTitle.setText(mVoteInfo.getContents().get(1).getSubject());

        if(data.showQuizResult) {
            //展示结果
            int winIndex = data.getRightAnswerIndex();
            if(winIndex == 0)
                mRedWin.setVisibility(View.VISIBLE);
            else if(winIndex == 1)
                mBlueWin.setVisibility(View.VISIBLE);

            GameConfig config = iSender.getConfig();
            if(selectedIndex == winIndex) {
                if(iSender != null)
                    iSender.addFragment(mData.getRid());
                //fill prizetext
                if(config != null)
                    fillTextWidthDrawable(mDesp, "", config.successGetFragmentTipOfInfo);
            } else {
                //fill prizetext
                if(config != null)
                    fillTextWidthDrawable(mDesp, "", config.successGetFragmentTipOfInfo);
            }
        } else {
            mRedState.setTag(0);
            mRedTitle.setTag(0);
            mRedRate.setTag(0);
            mRedState.setOnClickListener(this);
            mRedLogo.setOnClickListener(this);
            mRedTitle.setOnClickListener(this);
            mRedRate.setOnClickListener(this);

            mBlueState.setTag(1);
            mBlueTitle.setTag(1);
            mBlueRate.setTag(1);
            mBlueState.setOnClickListener(this);
            mBlueLogo.setOnClickListener(this);
            mBlueTitle.setOnClickListener(this);
            mBlueRate.setOnClickListener(this);
        }

        updateVSState();

        if(data.isCardFold()) {
            mGuessLayout.setVisibility(GONE);
        }
        switchFoldState(!data.isCardFold());

        UmengUtils.reportUmengEvent(mContext, UmengUtils.SHOW_PK, UmengUtils.appendLabels(mData.title, mChannelDetail.videoid, mChannelDetail.videoTitle));
    }

    private void updateOptionState(boolean isRed, boolean state) {
        if(isRed) {
            mRedState.setTag(R.id.vs_selected_state, state);
            mRedLogo.setTag(R.id.vs_selected_state, state);
            mRedTitle.setTag(R.id.vs_selected_state, state);
            mRedRate.setTag(R.id.vs_selected_state, state);
        } else {
            mBlueState.setTag(R.id.vs_selected_state, state);
            mBlueLogo.setTag(R.id.vs_selected_state, state);
            mBlueTitle.setTag(R.id.vs_selected_state, state);
            mBlueRate.setTag(R.id.vs_selected_state, state);
        }
    }

    private void updateVSState() {
        if (mVoteInfo.isVoted(getContext())) {
            if (mVoteInfo.getVotedIndex(getContext()) == 0) {
                mRedState.setImageResource(R.drawable.icon_thumbreds);
                updateOptionState(true, true);
                mBlueState.setImageResource(R.drawable.icon_thumblue);
                updateOptionState(false, false);
            } else {
                mRedState.setImageResource(R.drawable.icon_thumbred);
                updateOptionState(true, false);
                mBlueState.setImageResource(R.drawable.icon_thumblues);
                updateOptionState(false, true);
            }
        } else {
            mRedState.setImageResource(R.drawable.icon_thumbred);
            updateOptionState(true, false);
            mBlueState.setImageResource(R.drawable.icon_thumblue);
            updateOptionState(false, false);
        }

        VoteItemInfo itemLeft = mVoteInfo.getContents().get(0);
        final int progress = (mVoteInfo.getTotalNum() == 0) ? 50 : Utils.calPercentInt(mVoteInfo.getTotalNum(), itemLeft.getNumber());

        mRedRate.setText(appendPercentStr(progress));
        mBlueRate.setText(appendPercentStr(100-progress));

        mDesp.setText(mVoteInfo.getTotalNum() + "人参与");

        mProgress.updateProgress(progress, true);
    }

    private VoteInfo parse(TimeLinePiece item) {
        VoteInfo info = new VoteInfo();
        info.setup(getContext(), item);
        return info;
    }

    @Override
    public void doNext() {
        if(mData.showQuizResult)
            return;
        if(iSender != null)
            iSender.startSync(mData.getRid(), false);
    }

    @Override
    public String getType() {
        return TYPE_GUESS;
    }

    @Override
    public void syncData(OptionResultModel response) {
        if(mData.showQuizResult)
            return;
        mVoteInfo.update(getContext());
        updateVSState();
    }

    @Override
    public void syncPreviewData(ReportResultModel result) {

    }

    @Override
    public boolean IsPreviewDataSynced() {
        return false;
    }

    @Override
    public void onClick(View v) {
        if(mData == null || !mData.isIllegal)
            return;
        int position = -1;
        if(v == mRedLogo)
            position = 0;
        else if(v == mBlueLogo)
            position = 1;
        else
            position = (int) v.getTag();

        boolean isRed = position == 0;

        String optionId = mData.getOptionId(position);
        reportOptionSelectEvent("option", optionId);

        String cancelId = null;
        if(selectedIndex >= 0)
            cancelId = mData.getOptionId(selectedIndex);
        if(selectedIndex == position)
            optionId = null;
        report(mData.getRid(), optionId, cancelId, true);

        DataManager.getInstance(getContext()).updateOptionCount(cancelId, true);
        DataManager.getInstance(getContext()).updateOptionCount(optionId, false);
        mVoteInfo.update(getContext());

        if (selectedIndex == position)
            selectedIndex = -1;
        else
            selectedIndex = position;

        UmengUtils.reportUmengEvent(getContext(), UmengUtils.TO_PK, UmengUtils.appendLabels(mData.getOptionValue(position), mData.title, mChannelDetail.videoid, mChannelDetail.videoTitle));

        DataManager.getInstance(getContext()).update(mData.getRid(), selectedIndex);

        updateVSState();
        boolean selected = (boolean) v.getTag(R.id.vs_selected_state);

        AnimatorHelper.voteAnimation(isRed ? mRedState : mBlueState , selected, isRed);
    }
}
